package cn.spream.jstudy.solr.dao.user.impl;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CloudSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import cn.spream.jstudy.solr.dao.user.UserDao;
import cn.spream.jstudy.solr.domain.user.User;

import java.io.IOException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: sjx
 * Date: 14-3-20
 * Time: 下午3:22
 * To change this template use File | Settings | File Templates.
 */
public class UserDaoSolrImpl implements UserDao {

    private CloudSolrServer userCloudSolrServer;

    @Override
    public void add(User user) throws IOException, SolrServerException {
        userCloudSolrServer.addBean(user);
    }

    @Override
    public void deleteById(long id) throws IOException, SolrServerException {
        userCloudSolrServer.deleteById(String.valueOf(id));
    }

    @Override
    public void update(User user) throws IOException, SolrServerException {
        add(user);
    }

    @Override
    public User getById(long id) throws SolrServerException {
        SolrQuery solrQuery = new SolrQuery();
        solrQuery.setQuery("id:" + id);
        solrQuery.setStart(0);
        solrQuery.setRows(1);
        QueryResponse queryResponse = userCloudSolrServer.query(solrQuery);
        List<User> users = queryResponse.getBeans(User.class);
        return users.size() > 0 ? users.get(0) : null;
    }

    @Override
    public List<User> find() throws SolrServerException {
        return userCloudSolrServer.query(new SolrQuery()).getBeans(User.class);
    }

    public void setUserCloudSolrServer(CloudSolrServer userCloudSolrServer) {
        this.userCloudSolrServer = userCloudSolrServer;
    }
}
